(function() {
'use strict';

angular
	.module('votingBackend')
	.controller('DashboardController', ['$scope', '$timeout', '$interval', 'Upload', 'toastr', '$http', 'userDataService', 'quizDataService', '$rootScope', '$location', '$state', 'localStorageService', DashboardController]);

	function DashboardController ($scope, $timeout, $interval, Upload, toastr, $http, userDataService, quizDataService, $rootScope, $location, $state, localStorageService) {

	//initialize quiz for ng-model to post to api
	var _init = function(){
		$scope.quiz = {
			name: '',
			quiz_type: 'survey',
			is_competition: 'false',
			requires_login: 'false',
			questions: [
				{
					name: '',
					unique_id: makeDeviceId(),
					question_type: 'quiz_single', //can also have 'quiz_multiple' and 'survey'
					description: '',
					answers: [
						{
							content: '',
							unique_id: makeDeviceId(),
							is_correct: false
						},
						{
							content: '',
							unique_id: makeDeviceId(),
							is_correct: false
						}
					]
				},
			]
		} 

		getAllUserData();

		if (localStorageService.get('activeQuizQr')){
			$rootScope.quizQrCode = localStorageService.get('activeQuizQr')
		}
	}

	_init();

	// var baseUrl = 'http://115.29.194.90:1234/'
	var baseUrl = 'http://localhost:1235/'


	//building the quiz

	$scope.emptyQuestion = {
		name: '',
		unique_id: makeDeviceId(),
		question_type: 'quiz_single',
		description: '',
		answers: [
			{
				unique_id: makeDeviceId(),
				content: '',
				is_correct: false
			},
			{
				unique_id: makeDeviceId(),
				content: '',
				is_correct: false
			},
		]
	}

	$scope.emptyAnswer = {
		unique_id: makeDeviceId(),
		content: '',
		is_correct: false
	}

	$scope.addNewQuestionToForm = function(event){
		console.log($scope.quiz)
		if ( $(event.target).hasClass('has-content') != true ) {
			$scope.emptyQuestion.unique_id = makeDeviceId();
			$scope.emptyQuestion.answers[0].unique_id = makeDeviceId();
			$scope.emptyQuestion.answers[1].unique_id = makeDeviceId();
			$scope.quiz.questions.push(angular.copy($scope.emptyQuestion));
			$(event.target).addClass('has-content');
		}
	}

	$scope.removeQuestion = function(event){
		var removeQuestionTargetIndex = event.target.dataset.id;
		document.getElementById('question-row-' + removeQuestionTargetIndex).remove();
		$scope.removeQuestionFromDb(removeQuestionTargetIndex);
		$scope.quiz.questions.splice(removeQuestionTargetIndex, 1);
		console.log($scope.quiz);
	}

	$scope.removeQuestionFromDb = function(removeQuestionTargetIndex){
		$http.put(baseUrl + 'question/delete', $scope.quiz.questions[removeQuestionTargetIndex])
		.success(function (data, status, headers) {
			console.log('question succesfully deleted');
			console.log(data)
		})
	}

	//this is the old version of adding answers which runs automatically when user types
	$scope.addNewAnswerToQuestion = function(event){
		if ( $(event.target).hasClass('has-content') != true ) {
			$scope.questionFormAnswers.push( $scope.questionFormAnswers[$scope.questionFormAnswers.length-1] +1 );
			$(event.target).addClass('has-content');
			var all = document.getElementsByTagName('')
		}
	}

	//this is the new version of adding answers which runs on click
	$scope.addAnswer = function(event){
		var parentId = event.target.dataset.parentid;
		var uniqueId = makeDeviceId()
		console.log(uniqueId)
		$scope.emptyAnswer.unique_id = uniqueId; 
		$scope.quiz.questions[parentId].answers.push( angular.copy($scope.emptyAnswer) );
		console.log($scope.quiz)
	}

	$scope.removeAnswer = function(event){
		var _checked = confirm('Are you sure you want to delete this answer choice?');
		if (_checked){
			var targetIndex = event.target.dataset.id;
			var parentId = event.target.dataset.parentid;
			$scope.removeAnswerFromDb(parentId, targetIndex);
			$scope.quiz.questions[parentId].answers.splice(targetIndex, 1);
		}
	}

	$scope.removeAnswerFromDb = function(parentId, targetIndex){
		console.log(parentId, targetIndex);
		$http.put(baseUrl + 'questionchoice/delete', $scope.quiz.questions[parentId].answers[targetIndex])
		.success(function (data, status, headers) {
			console.log(data);
			console.log('Answer Choice Succesfully Deleted');
		})
	}

	$scope.setQuestionType = function(targetQuestion, targetType) {
		//change whether question can accept single or multiple answers
		//dom checkboxes are linked through ng-show to data type
		$scope.quiz.questions[targetQuestion].question_type = targetType;
		//clear out all correct answers when changing between single and multiple
		for (var i = 0; i < $scope.quiz.questions[targetQuestion].answers.length; i ++){
			$scope.quiz.questions[targetQuestion].answers[i].is_correct = false;
		} 

		// !! later add additional validations to retain selected answer choices when switching between questions types
	}

	$scope.returnModelString = function(index){
		console.log(index);
		return index;
	}

	function getUserActivity(){
		userDataService.provideAllUserActivity($scope.currentUser).then(function (){
			$scope.userActivity = userDataService.userData.activity;
			for (var i = 0; i < $scope.userData.activity.length; i++){
				for (var j = 0; j < $scope.userData.quizzes.length; j++){
					if (!$scope.userData.quizzes[j].activity){
						$scope.userData.quizzes[j].activity = []
					}
					
					if ($scope.userData.activity[i].quiz.id == $scope.userData.quizzes[j].id){
						$scope.userData.quizzes[j].activity.push($scope.userData.activity[i])
					}
					
				}
			}
		})	
	}

	//$timeout(function(){console.log("logging activeQuiz")}, 3000);
	//$timeout(function(){console.log($scope.activeQuiz.activity[0].createdAt.substring(0,10))}, 3000);


	//get data from from service to provide list of quizzes and questions

	//turn this into a socket connection ? 
	function getAllUserData(){
		userDataService.provideAllUserData($scope.currentUser).then(function () {
			$scope.userData = userDataService.userData;
			$scope.userName = $scope.userData.name;
			$scope.userQuizzes = $scope.userData.quizzes;
			//provide default state of active quiz
			console.log('logging $scope.userData');
			console.log($scope.userData);
			console.log('running reviewQuiz() to provide default state of quiz');
			$scope.reviewQuiz();
			//rearrange data to easily access quizzes
			//can probably improve the performance with a recursive sort method
			getUserActivity();
			
		})
	}


	//this counter prevents double submissions on capitalized letters, as shit key doesn't change the length
	//is there a less hacky way of doing this?
	$scope.titleChangeCounter = 0;

	$scope.createQuizTitle = function(){
		if ($scope.titleChangeCounter == 0) {
			$scope.createNewQuiz();
			$scope.triggerQuizUpdate();
			console.log($state);
			$scope.titleChangeCounter += 1;
		}
	}
	//functions for create quiz page, including live update and live delete

	//$scope.triggerQuizUpdate()

	//send a new quiz to the server and save its data to the db
	$scope.createNewQuiz = function() {
		//console.log('quiz saved locally in angular model')
		//console.log($scope.quiz)

		var quizLength = function() {
			return document.querySelectorAll('.question-row').length;
		}

		var currentQuizLength = quizLength();
		var currentQuizQuestions = []

		//this may need to be moved out of the scope of the parent function

		//build data into structure which can be sent to api
		for (var i = 0; i < currentQuizLength-1; i++){
			var questionKey = i;
			//delete lines remove tracking ids so that they don't get saved to db
			$scope.quiz.questions[questionKey].unique_id = makeDeviceId();
			currentQuizQuestions.push($scope.quiz.questions[questionKey])

			for (var j = 0; j < $scope.quiz.questions[questionKey].answers.length; j++){
				$scope.quiz.questions[questionKey].answers[j].unique_id = makeDeviceId();
			}

			var currentQuestionAnswers = []

			//angular.forEach( $scope.quiz.questions[questionKey].answers, function (value, key) {
			//	this.push(value);
			//}, currentQuestionAnswers);	

			//$scope.quiz.questions[questionKey].answers = currentQuestionAnswers;	

		}
		
		var newQuiz = {
			user: $scope.currentUser,
			name: $scope.quiz.name,
			length: currentQuizLength,
			is_competition: $scope.quiz.is_competition,
			requires_login: $scope.quiz.requires_login,
			questions: currentQuizQuestions
		}

		//console.log('quiz being sent to server')
		//console.log(newQuiz);
		
		//for production
		//$http.post('http://115.29.194.90:1234/quiz/create', newQuiz)
		//for development
		$http.post(baseUrl + 'quiz/create', newQuiz)
			.success(function (data, status, headers) {
				console.log('quiz returned from server')
				$scope.currentQuiz = data;
				toastr.success('New quiz successfully saved! Keep on adding questions!', 'Success', {
					closeButton: true
				});
			}).error(function (data, status, headers) {
				console.log(data, status, headers)
				if (status == 400){
					toastr.warning('Please make sure that your quiz has a title.', 'Warning', {
						closeButton: true
					});
				}
				else {
					toastr.error('Error establishing network connection. Please reload page and try again.', 'Error', {
						closeButton: true
					});
				}
		})
	}

	$scope.triggerQuizUpdate = function(){
		var updateQuiz = $interval(function(){
			$scope.updateQuizLive();
			if ($state.current.name != 'dashboard.create'){
				$interval.cancel(updateQuiz)
			}
		}, 30000);
	}

	function makeDeviceId() {
		var text = "";
	    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

	    for( var i=0; i < 32; i++ )
	        text += possible.charAt(Math.floor(Math.random() * possible.length));

	    return text;
	}



	

	$scope.currentQuiz; 

	$scope.updateQuizLive = function(){
		console.log('updating this quiz')
		//deep copy scope.quiz before removing the final question and updating
		$.extend($scope.currentQuiz, $scope.quiz);
		//console.log($scope.currentQuiz);
		//$scope.currentQuiz.questions[$scope.currentQuiz.question.length - 1]

		var quizLength = function() {
			return document.querySelectorAll('.question-row').length;
		}

		var currentQuizLength = quizLength();
		var currentQuizQuestions = []

		//this may need to be moved out of the scope of the parent function

		//build data into structure which can be sent to api
		for (var i = 0; i < currentQuizLength-1; i++){
			var questionKey = i;
			//delete lines remove tracking ids so that they don't get saved to db
			//$scope.currentQuiz.questions[questionKey].unique_id = Math.floor(Math.random()*1000000000);
			currentQuizQuestions.push($scope.currentQuiz.questions[questionKey])

			for (var j = 0; j < $scope.currentQuiz.questions[questionKey].answers.length; j++){
				//$scope.currentQuiz.questions[questionKey].answers[j].unique_id = Math.floor(Math.random()*1000000000);
			}
		}

		$scope.currentQuiz.questions = currentQuizQuestions;

		//$scope.currentQuiz['questions'] = $scope.quiz.questions;
		console.log($scope.currentQuiz);
		
		$http.put(baseUrl + 'quiz/createOrUpdate', $scope.currentQuiz)
			.success(function (data, status, headers) {
				toastr.info('Quiz successfully updated', 'Success', {
						closeButton: true
					});
				console.log(data)
			}).error(function (data, status, headers) {
				alert('Error Updating Quiz. Please Try Again Later')
				console.log(data, status, headers)
		})
	}

	$scope.updateQuizModificationsLive = function(){
		
	}

	$scope.letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'];
	$scope.numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15'];

	//function for the review/edit/delete quiz page

	$scope.reviewQuiz = function ($event) {
		//conditional to set data and style of active quiz on page load and on click
		if ($scope.activeQuiz){
			$scope.activeQuiz = $scope.userData.quizzes[this.$index];
			
		} else {
			$scope.activeQuiz = $scope.userData.quizzes[0];
			var currentQuizzesAlt = document.getElementsByClassName('sidebar-quiz');
			$timeout(function(){$(currentQuizzesAlt[0]).addClass('active-state')},100);
			//localStorageService.set('activeQuiz', $scope.activeQuiz);
		}
		localStorageService.set('activeQuiz', $scope.activeQuiz);

		//set style of active quiz and remove active state styles of other quizzes
		var targetIndex = this.$index;
		var currentQuizzes = document.getElementsByClassName('sidebar-quiz');
		
		for (var i=0; i<currentQuizzes.length; i++){
			$(currentQuizzes[i]).removeClass('active-state');
		};

		$(currentQuizzes[targetIndex]).addClass('active-state');
	
	}

	$scope.editActiveQuiz = function() {
		//make deep copy of active quiz which can be modified without effecting orig data
		//this will be discarded on discard and sent to db on confirm
		$scope.activeQuizModified = $.extend(true, {}, $scope.activeQuiz);
	}

	$scope.discardQuizModifications = function () {
		var checkMod = confirm('Are you sure you want to discard modifictions?')
		if (checkMod) {
			//make api call to revert the state of active quiz to the database quiz
			//console.log($scope.activeQuizIndex)
			var targetId = $scope.activeQuiz.id;
			$scope.activeQuizModified = {};
			$state.go('dashboard.review.view');
		}
	}

	$scope.updateQuiz = function() {
		var currentRecord = $scope.activeQuizModified.id
		console.log($scope.activeQuizModified)
		$http.put(baseUrl + 'quiz/update', $scope.activeQuizModified)
			.success(function (data, status, headers) {
				alert('Quiz Succesfully Updated');
				//getAllUserData();
				$state.go('dashboard.review.view');
				$.extend($scope.activeQuiz, $scope.activeQuizModified);
				console.log($scope.userQuizzes)
			}).error(function (data, status, headers) {
				alert('Error Updating Quiz. Please Try Again Later')
				console.log(data, status, headers)
		})
	}

	$scope.deleteQuiz = function() {
		var currentRecord = $scope.activeQuizModified.id
		$http.put(baseUrl + 'quiz/delete', $scope.activeQuizModified)
		.success(function (data, status, headers) {
			alert('Quiz Succesfully Deleted');

			//modify front end to get rid of deleted quiz and reset first quiz as active state
			//modify appearance
			$scope.activeQuiz = $scope.userData.quizzes[0];
			var currentQuizzesAlt = document.getElementsByClassName('sidebar-quiz');
			$timeout(function(){$(currentQuizzesAlt[0]).addClass('active-state')},100);

			//modify site-wide data structure pulled from api
			for (var i = 0; i < $scope.userQuizzes.length; i++){
				if ($scope.userQuizzes[i].id == $scope.activeQuizModified.id) {
					delete $scope.userQuizzes[i];
				}
			}

			//add something in here where you reload all the dynamic data on the page after updating something
			
			//go back to view state
			$state.go('dashboard.review.view');
		}).error(function (data, status, headers) {
			alert('Error Deleting Quiz. Please Try Again Later')
			console.log(data, status, headers)
		})
		//$scope.$apply();
	}


	//get qr code for quiz / later save instance of quiz to db
	$rootScope.quizQrCode;
	$scope.qrData = {}

	$scope.getQuizCode = function(){
		$scope.qrData['userName'] = $scope.userName;
		$scope.qrData['id'] = $scope.activeQuiz.id;

		//console.log($scope.qrData);

		//set image url to pull qr code with proper params from api
		//for production
		//$scope.quizQrCode = 'http://115.29.194.90:1234/qr?userName=' + $scope.qrData.userName + '&id=' + $scope.qrData.id;
		//for development
		console.log('qr data')
		console.log($scope.qrData);
		$rootScope.quizQrCode = baseUrl + 'qr?userName=' + $scope.qrData.userName + '&id=' + $scope.qrData.id + '&voteId=' + $scope.qrData.voteId;
		localStorageService.set('activeQuizQr', $rootScope.quizQrCode)
	}

	$scope.quizInstanceSettings = {
		hasTimeLimit: false,
		timeLimit: null,
		displayResults: false,
		displaySocial: false,
		hasDeadline: false,
		activeTimeStart: null,
		activeTimeEnd: null,
		allowUsers: 'require',
		showAnswers: false,
	};

	$scope.launchQuizInstance = function(type){
		console.log('creating quiz instance')
		console.log($scope.quizInstanceSettings);
		$http.post(baseUrl + 'vote', {
			quiz: $scope.activeQuiz.id,
			activeQuestion: $scope.activeQuiz.questions[0].id,
			voteType: type,
			userId: $scope.userData.id,
			//vote instance settings from modal form
			hasTimeLimit: $scope.quizInstanceSettings.hasTimeLimit,
			timeLimit: $scope.quizInstanceSettings.timeLimit,
			displayResults: $scope.quizInstanceSettings.displayResults,
			displaySocial: $scope.quizInstanceSettings.displaySocial, 
			hasDeadline: $scope.quizInstanceSettings.hasDeadline,
			activeTimeStart: $scope.quizInstanceSettings.activeTimeStart,
			activeTimeEnd: $scope.quizInstanceSettings.activeTimeEnd,
			requireLogin: $scope.quizInstanceSettings.allowUsers,
			showAnswers: $scope.quizInstanceSettings.showAnswers

		}).then(function(response){
			// POST succesful
			console.log($scope.quizInstanceSettings);
			console.log(response);
			$scope.qrData['voteId'] = response.data.id
			localStorageService.set('voteId', response.data.id);
			// redirect to qr code page or qr code state with link
			$scope.getQuizCode();
   			//change state on callback function for smoother looking animation?
   			if (type=='live'){
   				$('#qr-modal-live').modal('toggle').on('hidden.bs.modal', function(e){
   				$state.go('^.^.^.launchlive')
   				});
   			}
   			if (type=='normal'){
   				$('#qr-modal-normal').modal('toggle').on('hidden.bs.modal', function(e){
   					$state.go('^.^.^.launchnormal')
   				})
   			}
		}, function(err){
			console.log(err)
			alert('There has been an error. Please try again later.')
		})
	}

	$scope.reviewResults = function($index){
		localStorageService.set('voteId', $scope.activeQuiz.activity[$index].id)
		$state.go('^.^.^.results.review')
	}

	//recent activity
	$scope.recentActivity = [
		{
			'date': '2015/08/26',
			'is_active': true,
			'quiz': 1,
			'participants': 25
		},
		{
			'date': '2015/08/24',
			'is_active': true,
			'quiz': 2,
			'participants': 12
		},
		{
			'date': '2015/08/26',
			'is_active': false,
			'quiz': 3,
			'participants': 2500
		},

	]

	//settings page
	$scope.isOwnPath = function(path){
		var path = '/' + path;
		return $location.path() == path
	}

	//modify settings page
	$scope.uploadPic = function(file) {
    	console.log(file)
    	file.upload = Upload.upload({
    		url: baseUrl + 'avatarimage/createnew',
    		fields: {user: $scope.userData.id},
    		file: file,
    	});

    	file.upload.then(function (response) {
    		$timeout(function () {
    			file.result = response.data;
    			console.log(file.result)
    		});
    	}, function (response) {
      		if (response.status > 0)
        	$scope.errorMsg = response.status + ': ' + response.data;
    	});
    }

    // USING DASHBOARD CONTROLLER FOR REVIEW AND LAUNCH FUNCTIONS - LOTS OF USEFUL INFORMATION SAVED IN SCOPE HERE
    // WILL REFACTOR LATER TO IMPROVE PERFORMANCE




}
	
})();